package com.jswlw.web.config;

import com.alibaba.fastjson.JSON;
import com.jswlw.common.BaseException;
import com.jswlw.common.Constants;
import com.jswlw.common.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object object, Exception exception) {
        log.error("程序异常:", exception);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            ModelMap result = new ModelMap();
            if (exception instanceof BaseException) {
                BaseException baseException = (BaseException) exception;
                result.put(Constants.CODE, baseException.getCode());
                result.put(Constants.MSG, baseException.getMessage());
            } else {
                result.put(Constants.CODE, ResponseStatus.BUSINESS_ERROR.getCode());
                result.put(Constants.MSG, "服务器错误");
            }

            writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
        } catch (IOException e) {
        } finally {
            try {
                writer.flush();
                writer.close();
            } catch (Exception e) {
                //这里可能会抛出异常，而这里的异常是不需要的，所以屏蔽掉
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.clear();
        return modelAndView;
    }
}
